package com.eastedu.superise.handler.basic;

import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.eastedu.manager.FileManager;
import com.eastedu.model.basic.ResourceFile;
import com.eastedu.repository.basic.po.BasicResourcePO;
import com.eastedu.superise.handler.AbstractHistoricalDataHandler;
import com.eastedu.utils.JsonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 文件归档
 * 冷存储范围：每年9月份，将五年前的 标红资源进行冷存处理，五年内的保持原来的存储方案, 排除幼儿园
 * 故事ID 90690
 *
 * @author zhangzhishuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BasicFileArchiveHistoricalDataHandler extends AbstractHistoricalDataHandler<BasicResourcePO> {
    private static final int CLASSROOM_RECORD = 1;
    private static final int PREPARE_LESSON_RECORD = 8;
    private static final int MODEL_LESSON_RECORD = 7;
    private static final List<Integer> CATEGORIES = ListUtil.of(CLASSROOM_RECORD, PREPARE_LESSON_RECORD, MODEL_LESSON_RECORD);

    private final FileManager fileManager;
    private final  ConcurrentHashSet<Long> resourceIds = new ConcurrentHashSet<>();


    @Override
    protected String getSql() {
        return "SELECT * FROM t_basic_resource WHERE create_time < 1567267200000 and category in( 1, 8, 7) AND study_section_code != 'XQ'";
    }

    @Override
    public void callback(BasicResourcePO po) throws SQLException {
        if (!CATEGORIES.contains(po.getCategory())) {
            return;
        }

        Set<String> fileIds = JsonUtil.parseList(po.getFilesJson(), ResourceFile.class)
                .stream()
                .filter(resourceFile -> "mp4".equalsIgnoreCase(resourceFile.getExtension()))
                .map(ResourceFile::getFileId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        boolean result = this.fileManager.fileArchive(fileIds);
        if (!result) {
            this.resourceIds.add(po.getId());
        }
        ThreadUtil.sleep(50);
    }

    @Override
    public void afterCompletion() {
        super.afterCompletion();
        log.info("文件归档失败的资源id: {}", this.resourceIds);
    }
}
